package com.wobangkj.common.api.file;

import com.wobangkj.common.util.file.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * 静态资源请求
 * 由原始的静态资源映射 转向 接口形式解析
 *
 * @author lu
 */

@Controller
@RequestMapping(value = "/static")
@Slf4j
public class StaticFileController {

	// 文件上传路径
	private final String UploadPath = "/common-service/static/file/";

	// 图片类型
	private final String[] imageTypes = {"jpg", "jpeg", "png"};

	@GetMapping(value = "/file/**")
	@ResponseBody
	public Object file(@RequestParam(required = false) Map<String, Object> params, HttpServletRequest request) throws UnsupportedEncodingException {

		String width    = Optional.ofNullable((String) params.get("width")).orElse("0");
		String height   = Optional.ofNullable((String) params.get("height")).orElse("0");
		String quality  = Optional.ofNullable((String) params.get("quality")).orElse("1");
		String multiple = Optional.ofNullable((String) params.get("multiple")).orElse("1");

		String url      = request.getRequestURL().toString();
		File   rootFile = new File("");
		// 文件名
		String   fileName  = url.substring(url.lastIndexOf("/") + 1);
		String[] fileNames = fileName.split("\\.");
		// 文件类型[简要判断方式]
		String fileType = fileNames[1];
		// 解码后的真实文件名
		fileName = URLDecoder.decode(fileNames[0], "utf-8") + "." + fileType;
		// 文件所在目录
		String UpLoadPath = rootFile.getAbsolutePath() + UploadPath;

		// 静态资源拦截, 分析
		if (!width.equals("0") || !height.equals("0") || !quality.equals("1") || !multiple.equals("1")) {
			String newFileName = width + "-" + height + "-" + multiple + "-" + quality + URLDecoder.decode(fileNames[0], "utf-8") + ".jpg";
			File   src         = new File(UpLoadPath + newFileName);
			// 解析后的文件存在判断
			if (!src.exists()) {
				// 不存在则创建
				ImageUtil.Tosmallerpic(UpLoadPath, UpLoadPath, fileName, newFileName, Integer.parseInt(width), Integer.parseInt(height), Float.parseFloat(quality), Integer.parseInt(multiple));
			}
			return fileCheck(src, fileType);
		}
		File src = new File(UpLoadPath + fileName);
		return fileCheck(src, fileType);
	}

	// 文件类型简要检测
	// 真实文件类型判断参考: https://blog.csdn.net/t894690230/article/details/51242110
	private Object fileCheck(File file, String type) {


		// 图片类型
		for (String imgType : imageTypes) {
			if (type.equalsIgnoreCase(imgType)) {
				return ResponseEntity
						.ok()
						//.headers(headers)
						.contentLength(file.length())
						.contentType(MediaType.IMAGE_JPEG)
						.body(new FileSystemResource(file));
			}
		}

		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		headers.add("Content-Disposition", "attachment;");
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");
		headers.add("Last-Modified", new Date().toString());
		headers.add("ETag", String.valueOf(System.currentTimeMillis()));
		return ResponseEntity
				.ok()
				.headers(headers)
				.contentLength(file.length())
				.contentType(MediaType.parseMediaType("application/octet-stream"))
				.body(new FileSystemResource(file));
	}
}
